package com.zhipu.balance.ui.vm.home

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import com.blankj.utilcode.constant.TimeConstants
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.TimeUtils
import com.brightek.thermallibrary.CString
import com.brightek.thermallibrary.ThermalService
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.zhipu.balance.R
import com.zhipu.balance.listener.ChooseClickCallback
import com.zhipu.balance.mobile.ResultEntity
import com.zhipu.balance.mobile.temporaryClass.DevCode
import com.zhipu.balance.mobile.temporaryClass.VersionUpdate
import com.zhipu.balance.pop.ChoosePopup
import com.zhipu.balance.remotedata.InterceptObserver
import com.zhipu.balance.remotedata.systemapi.SystemApiService
import com.zhipu.balance.ui.home.GeneralBalanceActivity
import com.zhipu.balance.ui.home.HomeActivity
import com.zhipu.balance.ui.home.calculate.corn.CornActivity
import com.zhipu.balance.ui.home.calculate.dami.DaMiActivity
import com.zhipu.balance.ui.home.calculate.rapeseed.RapeseedActivity
import com.zhipu.balance.ui.home.calculate.rice.RiceActivity
import com.zhipu.balance.ui.home.calculate.soybean.SoybeanActivity
import com.zhipu.balance.ui.home.calculate.wheat.WheatActivity
import com.zhipu.balance.ui.home.record.RecordActivity
import com.zhipu.balance.ui.home.revise.ReviseActivity
import com.zhipu.balance.ui.home.system.SystemSettingActivity
import com.zhipu.balance.ui.vm.BaseViewModel
import com.zhipu.balance.utils.InitializeUtils
import com.zhipu.balance.utils.dialog.CommonDialog
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.*


/**
 * 首页的VM
 */
class HomeViewModel(mSystemApiService : SystemApiService) : BaseViewModel(mSystemApiService){

    init {
        /**
         * 获取设备序列号
         */
        if (TextUtils.isEmpty(SPUtils.getInstance().getString("DeviceCode"))){
            getDeviceCode()
        }
        /**
         * 版本更新
         */
        getVersionUpdate()
        /**
         *
         */
        InitializeUtils.setThermalService(object : ThermalService(object : Handler(Looper.getMainLooper()) {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                when(msg.what){
                    CString.usb_Connected ->{
                        InitializeUtils.getDefaultMaker()?.show(ActivityUtils.getTopActivity().resources.getString(R.string.txtUsbConnected))
                        InitializeUtils.setLinkPrinter(true)
                    }
                    CString.usb_Connecting ->{
                        InitializeUtils.getDefaultMaker()?.show(ActivityUtils.getTopActivity().resources.getString(R.string.txtUsbConnecting) + msg.getData().getString(CString.reData))
                    }
                    CString.usb_DisConnected ->{
                        InitializeUtils.getDefaultMaker()?.show(ActivityUtils.getTopActivity().resources.getString(R.string.txtUsbDisConnected))
                        InitializeUtils.setLinkPrinter(false)
                    }
                    CString.usb_ReadData ->{
                        val usbReadData = msg.data.getString(CString.reData) //接受msg传递过来的参数
                        InitializeUtils.getDefaultMaker()?.show(ActivityUtils.getTopActivity().resources.getString(R.string.txtUsbReadData) + usbReadData)
                        InitializeUtils.setLinkPrinter(false)
                    }
                }
            }
           },ActivityUtils.getTopActivity()){
        })


        if(SPUtils.getInstance().getLong("NumberedDate") > 0){
            val DAY = TimeUtils.getTimeSpan(SPUtils.getInstance().getLong("NumberedDate"), TimeUtils.getNowMills(), TimeConstants.DAY)
            if (DAY > 0) {
                SPUtils.getInstance().put("number", 1)
                SPUtils.getInstance().put("NumberedDate", TimeUtils.getNowMills())
            }
        } else {
            SPUtils.getInstance().put("number", 1)
            SPUtils.getInstance().put("NumberedDate", TimeUtils.getNowMills())
        }

    }

    /**
     * 获取设备序列号
     */
    fun getDeviceCode(){
        val devCode = DevCode()
        devCode.setKey(DeviceUtils.getAndroidID() + "," + DeviceUtils.getMacAddress().uppercase(Locale.getDefault()))
        devCode.setEndpointType("1")
        //时间戳
        val mTimeStamp = TimeUtils.getNowMills()
        var json = "${mGson.toJson(devCode)}&${mTimeStamp}"
        var observable = mSystemApiService.DeviceCode(toHexString(json),mTimeStamp,devCode)
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(object : InterceptObserver<String>() {
            /**
             * 成功数据data
             */
            override fun <T> onNextData(resultEntity: ResultEntity<T>?) {
                println(resultEntity?.message.toString())
                SPUtils.getInstance().put("DeviceCode", resultEntity?.message.toString())
            }

            /**
             * 错误网络
             */
            override fun onErrorNet(t: Throwable?, netMsg: String?) {

            }
        })
    }

    /**
     * 版本更新
     */
    fun getVersionUpdate(){
        var observable = mSystemApiService.version()
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(object : Observer<VersionUpdate>{

            override fun onSubscribe(d: Disposable) {


            }

            override fun onNext(versionUpdate: VersionUpdate) {
                CommonDialog.showAccordingToUpdate(versionUpdate)
            }


            override fun onError(e: Throwable) {

            }


            override fun onComplete() {
            }
        })
    }

    /**
     * 普通\n天平
     */
    fun GeneralBalance(){
        ActivityUtils.startActivity(GeneralBalanceActivity::class.java)
        ActivityUtils.finishActivity(HomeActivity::class.java)
    }

    /**
     * 天平校正
     */
    fun BalanceCorrection(){
        ActivityUtils.startActivity(ReviseActivity::class.java)
    }

    /**
     * 功能计算
     */
    fun FunctionalComputing(){
        var mChoosePopup = ChoosePopup(object : ChooseClickCallback {
            override fun onChooseClickCallback(mInt: Int) {
                when(mInt){
                    0 ->{
                        //稻谷
                        ActivityUtils.startActivity(RiceActivity::class.java)
                    }
                    1 ->{
                        //小麦
                        ActivityUtils.startActivity(WheatActivity::class.java)
                    }
                    2 ->{
                        //玉米
                        ActivityUtils.startActivity(CornActivity::class.java)
                    }
                    3 ->{
                        //大米
                        ActivityUtils.startActivity(DaMiActivity::class.java)
                    }
                    4 ->{
                        //大豆
                        ActivityUtils.startActivity(SoybeanActivity::class.java)
                    }
                    5 ->{
                        //油菜籽
                        ActivityUtils.startActivity(RapeseedActivity::class.java)
                    }
                }
            }
        })
        XPopup.Builder(ActivityUtils.getTopActivity())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .autoOpenSoftInput(false)
            .asCustom(mChoosePopup)
            .show();
    }


    /**
     * 使用记录
     */
    fun UsageRecord(){
        ActivityUtils.startActivity(RecordActivity::class.java)
    }


    /**
     * 系统设置
     */
    fun SystemSetting(){
        ActivityUtils.startActivity(SystemSettingActivity::class.java)
    }

}